package com.zyw.security.shiro.stateless.realm;

import com.zyw.security.shiro.stateless.StatelessAccountService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;

/**
 * shiro state less realm
 *
 * @author zhangyw
 * @date 2017/12/6 14:24
 */
public class StatelessRealm extends AuthorizingRealm {

    /**
     * 用户查询service
     */
    private StatelessAccountService accountService;

    @Override
    public boolean supports(AuthenticationToken token) {
        //仅支持StatelessToken类型的Token
        return token != null && token instanceof StatelessToken;
    }

    /**
     * 认证方法 （调用 subject.login()方法后，触发）
     *
     * @param authenticationToken 令牌
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        StatelessToken statelessToken = (StatelessToken) authenticationToken;

        SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(statelessToken.getUsername(), getName());

        return new SimpleAuthenticationInfo(principalCollection, statelessToken.getPassword());

    }

    /**
     * 授权方法
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        //根据用户名查找角色，请根据需求实现
        String username = (String) principals.getPrimaryPrincipal();
        return authorizationInfo;
    }
}
